<script setup lang="ts">
import { getCodeImg } from '@/api/login'
import { useRenderIcon } from '@/components/ReIcon/src/hooks'
import { getConfig } from '@/config'
import { useDataThemeChange } from '@/layout/hooks/useDataThemeChange'
import { useLayout } from '@/layout/hooks/useLayout'
import { initRouter } from '@/router/utils'
import { useUserStoreHook } from '@/store/modules/user'
import { decrypt, encrypt } from '@/utils/jsencrypt'
import { message } from '@/utils/message'
import Lock from '@iconify-icons/ri/lock-fill'
import User from '@iconify-icons/ri/user-3-fill'
import type { FormInstance } from 'element-plus'
import Cookies from 'js-cookie'
import { onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import Motion from './utils/motion'
import { loginRules } from './utils/rule'

defineOptions({
  name: 'Login',
})

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const formRef = ref<FormInstance>()

const { initStorage } = useLayout()
initStorage()

const { dataThemeChange } = useDataThemeChange()
dataThemeChange()

const config = getConfig()

const ruleForm = reactive({
  username: '',
  password: '',
  code: '',
  uuid: '',
  rememberMe: false,
})

const codeUrl = ref('')

// 验证码开关
const captchaEnabled = ref(false)

const onLogin = async () => {
  const ok = await formRef.value.validate()
  if (!ok) return

  loading.value = true
  try {
    if (ruleForm.rememberMe) {
      Cookies.set('username', ruleForm.username, { expires: 30 })
      Cookies.set('password', encrypt(ruleForm.password), {
        expires: 30,
      })
      Cookies.set('rememberMe', `${ruleForm.rememberMe}`, { expires: 30 })
    } else {
      // 否则移除
      Cookies.remove('username')
      Cookies.remove('password')
      Cookies.remove('rememberMe')
    }
    useUserStoreHook()
      .loginByUsername({ ...ruleForm })
      .then(() => {
        initRouter().then(() => {
          message('登录成功', { type: 'success' })
          if (route.query.redirect) {
            router.push(String(route.query.redirect))
          } else {
            router.push('/welcome')
          }
        })
      })
      .catch(() => {
        if (captchaEnabled.value) {
          getCode()
          ruleForm.code = ''
        }
      })
  } finally {
    loading.value = false
  }
}

function getCookie() {
  const username = Cookies.get('username')
  const password = Cookies.get('password')
  const rememberMe = Cookies.get('rememberMe')
  ruleForm.username = username ?? ''
  ruleForm.password = password ? decrypt(password) : ''
  ruleForm.rememberMe = rememberMe ? Boolean(rememberMe) : false
}

getCookie()

const getCode = async () => {
  const { data } = await getCodeImg()
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img
    ruleForm.uuid = data.uuid
  }
}

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === 'Enter') {
    onLogin()
  }
}

onMounted(() => {
  // getCode()
  window.document.addEventListener('keypress', onkeypress)
})

onBeforeUnmount(() => {
  window.document.removeEventListener('keypress', onkeypress)
})
</script>

<template>
  <div class="select-none login-container">
    <div class="login-box">
      <h1 class="login-title mb-4 text-primary">人工智能基础平台</h1>
      <div class="login-form">
        <el-form ref="formRef" :model="ruleForm" :rules="loginRules" size="large">
          <Motion :delay="100">
            <el-form-item
              :rules="[
                {
                  required: true,
                  message: '请输入用户名称',
                  trigger: 'blur',
                },
              ]"
              prop="username"
            >
              <el-input
                v-model="ruleForm.username"
                class="shadow"
                clearable
                placeholder="请输入用户名称"
                :prefix-icon="useRenderIcon(User)"
              />
            </el-form-item>
          </Motion>
          <Motion :delay="150">
            <el-form-item prop="password">
              <el-input
                v-model="ruleForm.password"
                class="shadow"
                clearable
                show-password
                placeholder="密码"
                :prefix-icon="useRenderIcon(Lock)"
              />
            </el-form-item>
          </Motion>
          <Motion :delay="200">
            <el-form-item v-if="captchaEnabled" prop="code">
              <div class="flex justify-between">
                <el-input
                  v-model="ruleForm.code"
                  class="shadow"
                  size="default"
                  auto-complete="off"
                  placeholder="验证码"
                  style="width: 63%"
                >
                  <template #prefix
                    ><svg-icon icon-class="validCode" class="el-input__icon input-icon"
                  /></template>
                </el-input>
                <div class="w-1/3">
                  <img :src="codeUrl" class="h-[32px]" @click="getCode" />
                </div>
              </div>
            </el-form-item>
          </Motion>
          <Motion :delay="200">
            <el-form-item class="remember-me">
              <el-checkbox v-model="ruleForm.rememberMe">记住密码</el-checkbox>
            </el-form-item>
          </Motion>
          <Motion :delay="250">
            <el-button
              class="w-full shadow-md"
              size="large"
              type="primary"
              color="#307BF6"
              :loading="loading"
              @click="onLogin"
            >
              登录
            </el-button>
          </Motion>
        </el-form>
      </div>
    </div>
    <p class="copyright">{{ config.CopyRight }}</p>
  </div>
</template>

<style lang="scss">
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.login-container {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.login-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  width: 360px;
  height: 380px;

  .login-form {
    width: 280px;
  }
}

.copyright {
  @apply absolute bottom-4 text-sm text-neutral-500;
}

@media screen and (max-width: 968px) {
  .login-form h2 {
    font-size: 2.4rem;
    margin: 8px 0;
  }

  .login-box {
    right: 50%;
    top: 50%;
    transform: translate(50%, -50%);
  }

  .copyright {
    bottom: 20px;
    left: 50%;
    transform: translate(-50%, 0);
  }

  .slogan {
    top: 85%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
